var timeout;

// 为每个选项卡绑定点击事件
document.querySelectorAll('.tab-button').forEach(function (tab) {
    tab.addEventListener('click', function () {
        // 移除所有选项卡的激活状态
        document.querySelectorAll('.tab-button').forEach(function (tab) {
            tab.classList.remove('active');
        });
        // 移除所有内容的激活状态
        document.querySelectorAll('.tab-content').forEach(function (content) {
            content.classList.remove('active');
        });

        // 添加激活状态到当前点击的选项卡和对应的内容
        var tabId = this.id.replace('tab-', '');
        document.getElementById('content-' + tabId).classList.add('active');
        this.classList.add('active');
    });
});
$(document).ready(function () {
    $('#searchForm').submit(function (e) {
        e.preventDefault(); // 防止表单提交
        var query = $('#searchInput').val();
        var csrftoken = $('input[name=csrfmiddlewaretoken]').val(); // 获取CSRF令牌
        $.ajax({
            url: '/search/',
            type: 'POST',
            data: {'q': query},
            headers: {
                'X-CSRFToken': csrftoken
            },
            success: function (data) {
                $('#searchResults').empty();
                $.each(data, function (index, item) {
                    var fullText = item.source + ' ' + item.name;
                    var displayText = fullText.length > 10 ? fullText.substring(0, 10) + '...' : fullText;

                    var li = $('<li>')
                        .attr('title', fullText)
                        .css('color', item.is_del === 0 ? 'red' : 'blue')
                        .css('cursor', 'pointer')
                        .hover(function() { $(this).attr('title', fullText); });

                    if (item.is_del === 0) {
                        li.css({
                            'text-decoration': 'line-through',
                            'opacity': '0.5'
                        });
                    }

                    li.text(displayText).appendTo('#searchResults');
                    if (item.is_del === 1) {
                        li.on('click', function(){
                            // 跳转到对应标签并高亮
                            var tabMap = { '社会': 'shehui', '电影': 'dianying', '游戏': 'game' };
                            var tabId = tabMap[item.source] || 'shehui';
                            $('#tab-' + tabId).click();
                            // 等待内容切换渲染
                            setTimeout(function(){
                                var btn = document.getElementById('button-' + item.id);
                                if (btn) {
                                    btn.classList.add('pulse-highlight');
                                    setTimeout(function(){ btn.classList.remove('pulse-highlight'); }, 1000);
                                    // 滚动至视图
                                    btn.scrollIntoView({behavior:'smooth', block:'center', inline:'center'});
                                }
                            }, 80);
                        });
                    }
                });
            }
        });
    });

    // 热点数据加载
    $('#openHot').on('click', function(){
        var csrftoken = $('input[name=csrfmiddlewaretoken]').val();
        $.ajax({
            url: '/hot/',
            type: 'POST',
            headers: { 'X-CSRFToken': csrftoken },
            success: function(list){
                var ul = $('#hotResults');
                ul.empty();
                list.forEach(function(item){
                    var li = $('<li>').text(item.source + ' ' + item.name).css('cursor','pointer');
                    li.on('click', function(){
                        var tabMap = { '社会': 'shehui', '电影': 'dianying', '游戏': 'game' };
                        var tabId = tabMap[item.source] || 'shehui';
                        $('#tab-' + tabId).click();
                        setTimeout(function(){
                            var btn = document.getElementById('button-' + item.id);
                            if (btn) {
                                btn.classList.add('pulse-highlight');
                                setTimeout(function(){ btn.classList.remove('pulse-highlight'); }, 1000);
                                btn.scrollIntoView({behavior:'smooth', block:'center', inline:'center'});
                            }
                        }, 80);
                    });
                    ul.append(li);
                });
            }
        });
    });
});

function handleClick(button) {
    var existingPopovers = document.querySelectorAll('.popover');
    existingPopovers.forEach(function (popover) {
        popover.style.display = 'none';
    });
    var buttonId = button.getAttribute('data-id');
    var popoverId = 'popover-' + buttonId;
    var popover = document.getElementById(popoverId);
    if (popover) {
        document.body.removeChild(popover);
    }
    popover = document.createElement('div');
    popover.classList.add('popover');
    popover.id = popoverId;
    document.body.appendChild(popover);
    // 先隐藏，待内容渲染后计算尺寸与位置
    popover.style.display = 'block';
    popover.style.visibility = 'hidden';
    // 获取当前激活标签的颜色选择器值
    var color = '#000000';
    if (typeof getActiveColorPicker === 'function') {
        var colorPicker = getActiveColorPicker();
        color = colorPicker ? colorPicker.value : '#000000';
    } else {
        // 兼容旧版本
        var colorPicker = document.getElementById('colorPicker');
        color = colorPicker ? colorPicker.value : '#000000';
    }
    var textarea = document.createElement('textarea');
    var count_cc = document.createElement('div');
    count_cc.textContent = '1';
    count_cc.title = '当前图层';

    // 仅设置输入占位
    textarea.placeholder = '输入文本';


    popover.appendChild(textarea);
    var cancelButton = document.createElement('button');
    cancelButton.textContent = '取消';
    cancelButton.classList.add('cancel-button');
    cancelButton.addEventListener('click', function () {
        popover.style.display = 'none';
    });
    // 判断是否为白板标签
    var activeTab = document.querySelector('.tab-button.active');
    var isWhiteboard = activeTab && activeTab.id === 'tab-baiban';

    var charCount = document.createElement('div');
    charCount.classList.add('char-count');
    charCount.textContent = '剩余:0小时';

    textarea.addEventListener('input', function () {
        var textLength = textarea.value.length;
        if (textLength > 140) {
            textarea.value = textarea.value.substring(0, 140);
        }
    });

    // 预创建但在白板下不展示的元素
    var confirmButton = document.createElement('button');
    confirmButton.textContent = '确认';
    confirmButton.classList.add('confirm-button');

    var addButton = document.createElement('button');
    addButton.textContent = '延长时间';
    addButton.classList.add('confirm-button');
    addButton.title = '使用1积分延长格子一小时'
    var buttonContainer = document.createElement('div');
    buttonContainer.classList.add('button-container1');
    count_cc.classList.add('count-text');

    // 用户信息（仅非白板显示）
    var ownerWrap = document.createElement('div');
    ownerWrap.style.display = 'none';
    ownerWrap.style.alignItems = 'center';
    ownerWrap.style.gap = '8px';
    ownerWrap.style.margin = '6px 0';
    var ownerAvatar = document.createElement('img');
    ownerAvatar.style.width = '24px'; ownerAvatar.style.height = '24px'; ownerAvatar.style.borderRadius = '50%';
    var ownerName = document.createElement('span'); ownerName.style.fontSize = '14px'; ownerName.style.fontWeight = '600';
    var ownerFans = document.createElement('span'); ownerFans.style.fontSize = '12px'; ownerFans.style.color = '#6b7280';
    var followBtn = document.createElement('button'); followBtn.classList.add('confirm-button'); followBtn.style.marginLeft = 'auto';
    followBtn.textContent = '关注';
    ownerWrap.appendChild(ownerAvatar); ownerWrap.appendChild(ownerName); ownerWrap.appendChild(ownerFans); ownerWrap.appendChild(followBtn);

    if (isWhiteboard) {
        // 白板仅显示文本框与取消按钮
        popover.appendChild(cancelButton);
    } else {
        // 其他标签显示完整按钮组
        popover.appendChild(ownerWrap);
        popover.appendChild(charCount);
        popover.appendChild(buttonContainer);
        buttonContainer.appendChild(confirmButton);
        buttonContainer.appendChild(cancelButton);
        buttonContainer.appendChild(count_cc);
        buttonContainer.appendChild(addButton);
    }

    // 渲染完成后，根据视窗与滚动计算位置
    var buttonRect = button.getBoundingClientRect();
    var scrollX = window.pageXOffset || document.documentElement.scrollLeft;
    var scrollY = window.pageYOffset || document.documentElement.scrollTop;
    var left = scrollX + buttonRect.left + (button.offsetWidth / 2) - (popover.offsetWidth / 2);
    var top = scrollY + buttonRect.bottom + 8; // 按钮下方 8px
    // 边界修正
    if (left < 8) left = 8;
    if (top < 8) top = 8;
    if (left + popover.offsetWidth > scrollX + window.innerWidth - 8) {
        left = scrollX + window.innerWidth - popover.offsetWidth - 8;
    }
    if (top + popover.offsetHeight > scrollY + window.innerHeight - 8) {
        top = scrollY + buttonRect.top - popover.offsetHeight - 8; // 放到上方
    }
    popover.style.left = left + 'px';
    popover.style.top = top + 'px';
    popover.style.visibility = 'visible';

    $.ajax({
        url: '/api/get_label_data/' + buttonId + '/',
        method: 'GET',
        data: {
            'buttonId': buttonId,
            'color': color,
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function (response) {
            if (response.success) {
                charCount.textContent = '剩余:' + response.hours_difference + '小时';
                if (response.data[0] === '0') {
                    if (response.data[2].user_points > -1) {
                        button.style.backgroundColor = color;
                    } else {
                        textarea.placeholder = '白板绘图至少需要1积分，当前积分不足';
                    }
                    textarea.placeholder = '白板不支持输入文本，一个格子消耗一积分';
                    confirmButton.disabled = true;
                    confirmButton.classList.add('cancel-button');
                    textarea.readOnly = true;
                    // 更新悬浮卡片积分/经验与进度条
                    var ptsEl = document.getElementById('uhc-points-text');
                    var expEl = document.getElementById('uhc-exp-text');
                    var expBar = document.getElementById('uhc-exp-bar');
                    if (ptsEl && expEl) {
                        ptsEl.textContent = response.data[2].user_points;
                        expEl.textContent = response.data[2].user_experience;
                        if (expBar) {
                            var expVal = parseInt(response.data[2].user_experience || 0, 10) || 0;
                            var percent = Math.max(0, Math.min(100, (expVal % 1000) / 1000 * 100));
                            expBar.style.width = percent + '%';
                        }
                    }
                }
                if (response.data[0] && response.data[0] !== '0') {
                    textarea.placeholder = response.data[0];
                    count_cc.textContent = response.data[1];
                } else {
                    count_cc.textContent = response.data[1];
                }
                if (response.data[1] >= 3 && response.data[0] !== '0') {
                    // 如果返回值大于等于3，禁用确认按钮
                    confirmButton.disabled = true;
                    confirmButton.classList.add('cancel-button');
                    textarea.disabled = true
                    textarea.readOnly = true;
                } else {
                    // 如果返回值小于3，启用确认按钮
                    confirmButton.disabled = false;
                    confirmButton.classList.add('confirm-button');
                }
                // 当非白板且存在像素拥有者，展示用户资料与关注按钮
                if (!isWhiteboard && response.data[2] !== '0' && response.data[0] !== '0') {
                    ownerWrap.style.display = 'flex';
                    ownerName.textContent = response.data[2];
                    ownerFans.textContent = '粉丝 ' + response.data[4];
                    ownerAvatar.src = response.url ? response.url : '/static/image/33.png';
                    // 修改人若为当前用户，不显示关注按钮
                    if (String(response.data[3].user_id) === String(response.data[7])) {
                        followBtn.style.display = 'none';
                    } else {
                        followBtn.style.display = '';
                        followBtn.textContent = response.data[6] ? '取消关注' : '关注';
                    }
                    followBtn.onclick = function(){
                        var csrftoken = document.querySelector('input[name=csrfmiddlewaretoken]').value;
                        $.ajax({
                            url: '/api/followed_data/',
                            method: 'POST',
                            data: {
                                'followBtn_1': response.data[3].user_id,
                                'followBtn_2': response.data[7],
                                'isFollowed': followBtn.textContent,
                                'csrfmiddlewaretoken': csrftoken
                            },
                            success: function (res) {
                                if (res.success) {
                                    if (res.data.isFollowedflag) {
                                        followBtn.textContent = '关注';
                                        ownerFans.textContent = '粉丝 ' + (parseInt(response.data[4], 10) - 1);
                                        response.data[4] = parseInt(response.data[4], 10) - 1;
                                    } else {
                                        followBtn.textContent = '取消关注';
                                        ownerFans.textContent = '粉丝 ' + (parseInt(response.data[4], 10) + 1);
                                        response.data[4] = parseInt(response.data[4], 10) + 1;
                                    }
                                }
                            }
                        });
                    };
                }
            } else {
                console.error('Error get_label_data:', response.error);
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX error:', error);
        }
    });

    confirmButton.addEventListener('click', function () {
        var text = textarea.value;
        // 获取当前激活标签的颜色选择器和时间输入组件值
        var color = '#ffffff'; // 默认使用白色
        var lasttime1 = 1;
        
        if (typeof getActiveColorPicker === 'function' && typeof getActiveLastTimeInput === 'function') {
            var colorPicker = getActiveColorPicker();
            console.log('确认按钮点击 - 获取的颜色选择器:', colorPicker);
            console.log('确认按钮点击 - 颜色选择器值:', colorPicker ? colorPicker.value : 'null');
            color = colorPicker ? colorPicker.value : '#ffffff'; // 默认使用白色
            
            var lasttime = getActiveLastTimeInput();
            lasttime1 = lasttime ? lasttime.value : 1;
        } else {
            // 兼容旧版本
            var colorPicker = document.getElementById('colorPicker');
            console.log('确认按钮点击 - 获取的颜色选择器(兼容模式):', colorPicker);
            console.log('确认按钮点击 - 颜色选择器值(兼容模式):', colorPicker ? colorPicker.value : 'null');
            color = colorPicker ? colorPicker.value : '#ffffff'; // 默认使用白色
            
            var lasttime = document.getElementById('last-time');
            lasttime1 = lasttime ? lasttime.value : 1;
        }
        var csrftoken = document.querySelector('input[name=csrfmiddlewaretoken]').value;

        $.ajax({
            url: '/api/process_data/' + buttonId + '/',
            method: 'POST',
            data: {
                'text': text,
                'color': color,
                'lasttime': lasttime1,
                'csrfmiddlewaretoken': csrftoken
            },
            success: function (response) {
                if (response.success) {
                    button.style.backgroundColor = color;
                    popover.style.display = 'none';
                    // 更新悬浮卡片积分/经验与进度条
                    var ptsEl = document.getElementById('uhc-points-text');
                    var expEl = document.getElementById('uhc-exp-text');
                    var expBar = document.getElementById('uhc-exp-bar');
                    if (ptsEl && expEl) {
                        ptsEl.textContent = response.data.user_points;
                        expEl.textContent = response.data.user_experience;
                        if (expBar) {
                            var expVal = parseInt(response.data.user_experience || 0, 10) || 0;
                            var percent = Math.max(0, Math.min(100, (expVal % 1000) / 1000 * 100));
                            expBar.style.width = percent + '%';
                        }
                    }
                } else {
                    textarea.placeholder = '绘图至少需要1积分，当前积分不足';
                    console.error('Error processing data:', response.error);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX error:', error);
            }
        });
    });

    // 延长时间
    addButton.addEventListener('click', function () {
        var csrftoken = document.querySelector('input[name=csrfmiddlewaretoken]').value;

        $.ajax({
            url: '/api/add_button/' + buttonId + '/',
            method: 'POST',
            data: {
                'csrfmiddlewaretoken': csrftoken
            },
            success: function (response) {
                if (response.success) {
                    popover.style.display = 'none';
                    // 更新悬浮卡片积分/经验与进度条
                    var ptsEl = document.getElementById('uhc-points-text');
                    var expEl = document.getElementById('uhc-exp-text');
                    var expBar = document.getElementById('uhc-exp-bar');
                    if (ptsEl && expEl) {
                        ptsEl.textContent = response.data.user_points;
                        expEl.textContent = response.data.user_experience;
                        if (expBar) {
                            var expVal = parseInt(response.data.user_experience || 0, 10) || 0;
                            var percent = Math.max(0, Math.min(100, (expVal % 1000) / 1000 * 100));
                            expBar.style.width = percent + '%';
                        }
                    }
                } else {
                    textarea.placeholder = '至少需要1积分，当前积分不足';
                    console.error('Error processing data:', response.error);
                }
            },
            error: function (xhr, status, error) {
                console.error('AJAX error:', error);
            }
        });

    });


    button.removeEventListener('mouseleave', function () {
        popover.style.display = 'none';
    });
    button.addEventListener('mouseleave', function () {
        clearTimeout(timeout);
    });
    popover.addEventListener('mouseover', function () {
        clearTimeout(timeout);
    });
}


document.body.addEventListener('mousemove', function (event) {
    var buttons = document.querySelectorAll('.button-grid button');
    var glowRadius = 20;
    buttons.forEach(function (button) {
        var buttonRect = button.getBoundingClientRect();
        var left = buttonRect.left;
        var top = buttonRect.top;
        var right = buttonRect.right;
        var bottom = buttonRect.bottom;
        if (event.clientX >= left - glowRadius && event.clientX <= right + glowRadius &&
            event.clientY >= top - glowRadius && event.clientY <= bottom + glowRadius) {
            button.classList.add('glow-button');
        } else {
            button.classList.remove('glow-button');
        }
    });
});

function toggleFollow() {
    var followBtn = document.getElementById('follow-btn');
    var followBtn_1 = followBtn.value.split("_")[0];
    var followBtn_2 = followBtn.value.split("_")[1];
    var isFollowed = followBtn.textContent;
    var csrftoken = document.querySelector('input[name=csrfmiddlewaretoken]').value;
    $.ajax({
        url: '/api/followed_data/',
        method: 'POST',
        data: {
            'followBtn_1': followBtn_1,
            'followBtn_2': followBtn_2,
            'isFollowed': isFollowed,
            'csrfmiddlewaretoken': csrftoken
        },
        success: function (response) {
            if (response.success) {
                if (response.data.isFollowedflag) {
                    document.getElementById('fans-count').textContent = '粉丝数量: ' + (parseInt(followBtn.value.split("_")[2], 10) - 1).toString();
                    document.getElementById('following-count').textContent = '关注数量: ' + parseInt(followBtn.value.split("_")[3], 10).toString();
                    document.getElementById('follow-btn').textContent = '关注';
                    document.getElementById('follow-btn').value = followBtn_1 + "_" + followBtn_2 + "_" + (parseInt(followBtn.value.split("_")[2], 10) - 1).toString() + "_" + followBtn.value.split("_")[3];
                } else {
                    document.getElementById('fans-count').textContent = '粉丝数量: ' + (parseInt(followBtn.value.split("_")[2], 10) + 1).toString();
                    document.getElementById('following-count').textContent = '关注数量: ' + parseInt(followBtn.value.split("_")[3], 10).toString();
                    document.getElementById('follow-btn').textContent = '取消关注';
                    document.getElementById('follow-btn').value = followBtn_1 + "_" + followBtn_2 + "_" + (parseInt(followBtn.value.split("_")[2], 10) + 1).toString() + "_" + followBtn.value.split("_")[3];
                }
            }
        },
        error: function (xhr, status, error) {
            console.error('AJAX error:', error);
        }
    });
}

// 刷新当前标签的绘图区域
function refreshCurrentTab() {
    // 获取当前激活的标签
    var activeTab = document.querySelector('.tab-button.active');
    if (!activeTab) {
        console.error('未找到激活的标签');
        return;
    }
    
    var tabId = activeTab.id; // 获取完整的标签ID
    var contentId = 'content-' + tabId.replace('tab-', ''); // 构建内容容器ID
    var buttonContainer = document.querySelector('#' + contentId + ' .button-grid');
    
    if (!buttonContainer) {
        console.error('未找到按钮容器:', contentId + ' .button-grid');
        return;
    }
    
    // 显示加载状态
    var loadingIndicator = document.createElement('div');
    loadingIndicator.id = 'refresh-loading';
    loadingIndicator.style.cssText = 'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(255,255,255,0.9); padding: 10px 20px; border-radius: 5px; font-weight: bold; z-index: 1000;';
    loadingIndicator.textContent = '刷新中...';
    buttonContainer.parentNode.appendChild(loadingIndicator);
    
    // 保存滚动位置
    var scrollX = buttonContainer.parentNode.scrollLeft;
    var scrollY = buttonContainer.parentNode.scrollTop;
    
    // 确定标签对应的参数
     var label = '';
     var tabIdClean = tabId.replace('tab-', ''); // 使用清理后的标签ID
     if (tabIdClean === 'shehui' || tabId === 'tab1') {
         label = 'shehui';
     } else if (tabIdClean === 'dianying' || tabId === 'tab2') {
         label = 'dianying';
     } else if (tabIdClean === 'game' || tabId === 'tab3') {
         label = 'game';
     } else if (tabIdClean === 'baiban' || tabId === 'tab4') {
         label = 'baiban';
     }
     
     // 发送AJAX请求获取最新的标签数据
     $.ajax({
         url: '/biaoqian/',
         type: 'POST',
         data: { q: label },
         headers: { 'X-CSRFToken': getCookie('csrftoken') },
        success: function(data) {
            // 更新绘图区域的数据
            if (data && data.length > 0) {
                // 遍历数据更新每个按钮的颜色和计数
                // 遍历所有按钮，根据返回的数据更新每个按钮的颜色
                var buttons = buttonContainer.querySelectorAll('button');
                buttons.forEach(function(button) {
                    var buttonId = button.getAttribute('data-button-id') || button.getAttribute('data-id') || button.id;
                    // 查找当前按钮的数据
                    var buttonData = data.find(function(item) {
                        return item.button.toString() === buttonId.toString();
                    });
                    
                    if (buttonData) {
                        button.style.backgroundColor = buttonData.color;
                        // 更新计数显示（如果有）
                        var countElement = button.querySelector('.count');
                        if (countElement) {
                            countElement.textContent = buttonData.count_c;
                        }
                    }
                });
            }
            
            console.log('数据刷新成功:', tabId, ', 获取到', data.length, '个按钮数据');
        },
        error: function() {
            console.error('刷新数据失败');
        },
        complete: function() {
            // 添加刷新动画效果
            buttonContainer.classList.add('refresh-highlight');
            
            // 恢复滚动位置
            buttonContainer.parentNode.scrollLeft = scrollX;
            buttonContainer.parentNode.scrollTop = scrollY;
            
            // 移除加载指示器
            loadingIndicator.remove();
            
            // 移除高亮效果
            setTimeout(function() {
                buttonContainer.classList.remove('refresh-highlight');
            }, 500);
            
            console.log('刷新完成:', tabId);
        }
    });
}

// 获取CSRF Token的辅助函数
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 添加刷新高亮动画样式
var style = document.createElement('style');
style.textContent = `
.refresh-highlight {
    animation: refresh-pulse 0.5s ease;
}

@keyframes refresh-pulse {
    0% { opacity: 0.7; }
    50% { opacity: 1; }
    100% { opacity: 1; }
}
`;
document.head.appendChild(style);

